package com.feibi.tappay_charge

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import tech.cherri.tpdirect.api.TPDCard
import tech.cherri.tpdirect.api.TPDEasyWallet
import tech.cherri.tpdirect.api.TPDEasyWalletResult
import tech.cherri.tpdirect.api.TPDLinePay
import tech.cherri.tpdirect.api.TPDLinePayResult
import tech.cherri.tpdirect.api.TPDServerType
import tech.cherri.tpdirect.api.TPDSetup
import tech.cherri.tpdirect.callback.TPDEasyWalletResultListener
import tech.cherri.tpdirect.callback.TPDLinePayResultListener

/** TappayChargePlugin */
class TappayChargePlugin : FlutterPlugin, MethodCallHandler {
    private lateinit var channel: MethodChannel
    private lateinit var context: Context

    companion object {
        var lineUri = ""
        var easyUri = ""
        var tpdLinePay: TPDLinePay? = null

        @SuppressLint("StaticFieldLeak")
        var tpdEasyWallet: TPDEasyWallet? = null

        fun handleIncomingIntent(context: Context, intent: Intent) {
            println("最後一步：")
            if (intent.dataString != null) {
                if (intent.dataString!!.contains(easyUri)) {
                    if (intent.dataString!!.startsWith("http")) {
                        tpdEasyWallet?.parseToEasyWalletResult(context, intent.data, object : TPDEasyWalletResultListener {
                            override fun onParseSuccess(tpdEasyWalletResult: TPDEasyWalletResult) {
                            }

                            override fun onParseFail(i: Int, s: String) {
                            }
                        })
                    }
                } else {
                    if (tpdLinePay == null)
                        tpdLinePay = TPDLinePay(context, lineUri)
                    tpdLinePay?.parseToLinePayResult(context, intent.data, object : TPDLinePayResultListener {
                        override fun onParseSuccess(p0: TPDLinePayResult?) {
                            println(
                                "parseToLinePayResult：onParseSuccess：${p0?.status} - ${p0?.recTradeId} - ${p0?.orderNumber}" +
                                        " - ${p0?.bankTransactionId} "
                            )
                        }

                        override fun onParseFail(p0: Int, p1: String?) {
                            println("parseToLinePayResult：onParseFail：$p0 - $p1")
                        }

                    })
                }
            }
        }

        fun initEasyWallet(context: Context, url: String) {
            easyUri = url
            tpdEasyWallet = TPDEasyWallet(context, easyUri)
        }

        fun initLinePay(url: String) {
            lineUri = url;
        }
    }

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        println("onAttachedToEngine ")
        context = flutterPluginBinding.applicationContext
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "tappay_charge")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        ////initTapPay
        if (call.method.equals("initTappay")) {
            val appId = call.argument<Int>("appId") ?: 0
            val appKey = call.argument<String>("appKey")
            val isSandBox = call.argument<Boolean>("isSandBox") ?: true
            TPDSetup.initInstance(context, appId, appKey, if (!isSandBox) TPDServerType.Production else TPDServerType.Sandbox)
        }
        ///添加信用卡
        else if (call.method.equals("getCardPrime")) {
            val cardNumber = call.argument<String>("cardNumber") ?: ""
            val dueMonth = call.argument<String>("dueMonth") ?: ""
            val dueYear = call.argument<String>("dueYear") ?: ""
            val ccv = call.argument<String>("ccv") ?: ""
            val card =
                TPDCard(context, StringBuffer(cardNumber), StringBuffer(dueMonth), StringBuffer(dueYear), StringBuffer(ccv))
            card.onSuccessCallback { prime, tpdCardInfoDto, s2, tpdMerchantReferenceInfoDto ->
                result.success(mapOf("success" to true, "prime" to prime))
            }.onFailureCallback { i, s ->
                result.error("$i", "$s", null);
            }
            card.createToken("UNKNOWN")
        }
        ///判断是否支持LinePay
        else if (call.method.equals("isLinePayAvailable")) {
            var isLinePayAvailable = TPDLinePay.isLinePayAvailable(context)
            result.success(mapOf("success" to isLinePayAvailable))
        }
        ///獲取LinePay - Prime
        else if (call.method.equals("getLinePayPrime")) {
            if (tpdLinePay == null)
                tpdLinePay = TPDLinePay(context, lineUri)
            tpdLinePay?.getPrime({
                result.success(mapOf("success" to true, "prime" to it))
            }, { i, s ->
                result.error("$i", s, null)
            })
        }
        ///LinePay - 支付
        else if (call.method.equals("redirectLinePay")) {
            val paymentUrl = call.argument<String>("paymentUrl")
            if (tpdLinePay == null)
                tpdLinePay = TPDLinePay(context, lineUri)
            tpdLinePay?.redirectWithUrl(paymentUrl)
            result.success(mapOf("success" to true))
        }
        ///獲取悠遊付 - Prime
        else if (call.method.equals("getEasyWalletPrime")) {
            tpdEasyWallet?.getPrime({
                result.success(mapOf("success" to true, "prime" to it))
            }, { i, s ->
                result.error("$i", s, null)
            })
        }
        ///悠遊付 支付
        else if (call.method.equals("redirectEasyWallet")) {
            val paymentUrl = call.argument<String>("paymentUrl")
            tpdEasyWallet?.redirectWithUrl(paymentUrl)
            result.success(mapOf("success" to true))
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }
}
